package SuperTaskManager;

import java.util.*;
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class XMLReader {

	public ArrayList<ITask>  getAllTaskStates(){
		  ArrayList<ITask> tasksList = new ArrayList<ITask>();
		  try {
			  File file = new File("tasks.xml");
			  DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			  DocumentBuilder db = dbf.newDocumentBuilder();
			  Document doc = db.parse(file);
			  doc.getDocumentElement().normalize();
			  System.out.println("Root element " + doc.getDocumentElement().getNodeName());
			  NodeList nodeLst = doc.getElementsByTagName("task");

			  String taskName;
			  String taskStatus;
			  
			  for (int s = 0; s < nodeLst.getLength(); s++) {
			    Node fstNode = nodeLst.item(s);
			    
			    if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
			  
			      Element fstElmnt = (Element) fstNode;
			      NodeList fstNmElmntLst = fstElmnt.getElementsByTagName("taskname");
			      Element fstNmElmnt = (Element) fstNmElmntLst.item(0);
			      NodeList fstNm = fstNmElmnt.getChildNodes();
			      taskName= fstNm.item(0).getNodeValue();
			      System.out.println("Task Name : "  + ((Node) fstNm.item(0)).getNodeValue());

			      NodeList lstNmElmntLst = fstElmnt.getElementsByTagName("taskstatus");
			      Element lstNmElmnt = (Element) lstNmElmntLst.item(0);
			      NodeList lstNm = lstNmElmnt.getChildNodes();
			      taskStatus =lstNm.item(0).getNodeValue();
			      System.out.println("Task Status : " + ((Node) lstNm.item(0)).getNodeValue());
			      
					try {
						ITask m = (ITask) Class.forName(taskStatus).newInstance();
						m.setTaskName(taskName);
						tasksList.add(m);
					} catch (InstantiationException e) {
						e.printStackTrace();
					} catch (IllegalAccessException e) {
						e.printStackTrace();
					} catch (ClassNotFoundException e) {
						e.printStackTrace();
					}		      

			    }

			  }
			  } catch (Exception e) {
			    e.printStackTrace();
			  }
		return tasksList;
			 }		
}